package com.ruoyi.cbs.project.controller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.cbs.project.domain.ProjectStop;
import com.ruoyi.cbs.project.domain.vo.StartStopProjectProcessReqVO;
import com.ruoyi.cbs.project.service.IProjectStopService;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 项目停工申请Controller
 * 
 * @author ruoyi
 * @date 2025-11-21
 */
@RestController
@RequestMapping("/workplace/stop")
public class ProjectStopController extends BaseController
{
    @Autowired
    private IProjectStopService projectStopService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询项目停工申请列表
     */
    @PreAuthorize("@ss.hasPermi('workplace:stop:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProjectStop projectStop)
    {
        startPage();
        List<ProjectStop> list = projectStopService.selectProjectStopList(projectStop);
        return getDataTable(list);
    }

    /**
     * 导出项目停工申请列表
     */
    @PreAuthorize("@ss.hasPermi('workplace:stop:export')")
    @Log(title = "项目停工申请", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ProjectStop projectStop)
    {
        List<ProjectStop> list = projectStopService.selectProjectStopList(projectStop);
        ExcelUtil<ProjectStop> util = new ExcelUtil<ProjectStop>(ProjectStop.class);
        util.exportExcel(response, list, "项目停工申请数据");
    }

    /**
     * 获取项目停工申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('workplace:stop:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(projectStopService.selectProjectStopById(id));
    }

    /**
     * 新增项目停工申请
     */
    @PreAuthorize("@ss.hasPermi('workplace:stop:add')")
    @Log(title = "项目停工申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ProjectStop projectStop)
    {
        return toAjax(projectStopService.insertProjectStop(projectStop));
    }

    /**
     * 修改项目停工申请
     */
    @PreAuthorize("@ss.hasPermi('workplace:stop:edit')")
    @Log(title = "项目停工申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ProjectStop projectStop)
    {
        return toAjax(projectStopService.updateProjectStop(projectStop));
    }

    /**
     * 删除项目停工申请
     */
    @PreAuthorize("@ss.hasPermi('workplace:stop:remove')")
    @Log(title = "项目停工申请", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(projectStopService.deleteProjectStopByIds(ids));
    }

    /**
     * 发起停工申请
     */
    @PreAuthorize("@ss.hasPermi('workplace:stop:edit')")
    @Log(title = "项目停工申请", businessType = BusinessType.UPDATE)
    @DeleteMapping("/startStopProjectProcess")
    public AjaxResult startStopProjectProcess(StartStopProjectProcessReqVO startStopProjectProcessReqVO) {
        // 获取请求携带的令牌
        String token = getToken(request);
        LoginUser user = new LoginUser();
        if (StringUtils.isNotEmpty(token)) {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            String userKey = getTokenKey(uuid);
            user = redisCache.getCacheObject(userKey);
        }
        return toAjax(projectStopService.startStopProjectProcess(user, startStopProjectProcessReqVO));
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    private String getTokenKey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

    // 令牌自定义标识
    @Value("${token.header}")
    private String header;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

}
